package com.example.listener;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebListener
public class CommonListener implements ServletContextListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("ServletContext上下文初始化");
        servletContextEvent.getServletContext().setAttribute("count", new HashMap<>());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        logger.info("ServletContext上下文初销毁");
        Map<String, Object> count =
                (Map<String, Object>) servletContextEvent.getServletContext().getAttribute("count");

        logger.info("访问人数:" + count.entrySet().size());
        Integer num = 0;
        for (Map.Entry<String, Object> item :
                count.entrySet()) {
            List<StringBuffer> list = (ArrayList) item.getValue();
            num += list.size();
        }
        logger.info("访问量:" + num);
    }
}
